package com.augrain.microframework.trace.instrument.client;

import com.augrain.microframework.core.spring.SpringUtils;
import com.augrain.microframework.core.util.IpUtils;
import com.augrain.microframework.core.util.StringUtils;
import com.augrain.microframework.trace.TraceConstant;
import com.augrain.microframework.trace.common.spanid.SpanIdGenerator;
import com.augrain.microframework.trace.context.TraceContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpRequest;
import org.springframework.http.client.ClientHttpRequestExecution;
import org.springframework.http.client.ClientHttpRequestInterceptor;
import org.springframework.http.client.ClientHttpResponse;

import java.io.IOException;

/**
 * trace rest http请求拦截器
 *
 * @author biaoy
 * @since 2021/08/22
 */
public class TraceClientHttpRequestInterceptor implements ClientHttpRequestInterceptor {

    private static final Logger LOGGER = LoggerFactory.getLogger(TraceClientHttpRequestInterceptor.class);

    @Override
    public ClientHttpResponse intercept(HttpRequest httpRequest, byte[] bytes, ClientHttpRequestExecution clientHttpRequestExecution) throws IOException {
        HttpHeaders headers = httpRequest.getHeaders();

        String traceId = TraceContext.getTraceId();
        if (StringUtils.isNotEmpty(traceId)) {
            headers.add(TraceConstant.TRACE_ID, traceId);
            headers.add(TraceConstant.SPAN_ID, SpanIdGenerator.generateNextSpanId());
            headers.add(TraceConstant.FROM_APP, SpringUtils.getApplicationName());
            headers.add(TraceConstant.FROM_IP, IpUtils.getLocalIp());
        } else {
            if (LOGGER.isDebugEnabled()) {
                LOGGER.debug("[TRACE]本地threadLocal变量没有正确传递traceId,本次调用不传递traceId");
            }
        }
        return clientHttpRequestExecution.execute(httpRequest, bytes);
    }
}
